"""6.0 Fix #2073: Creation de la table accounting_closure

Revision ID: 6bb1388dbe67
Revises: ea3ee333c241
Create Date: 2020-11-02 17:55:18.357623

"""

# revision identifiers, used by Alembic.
revision = "6bb1388dbe67"
down_revision = "ea3ee333c241"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

import datetime

from caerp.models.accounting.accounting_closures import AccountingClosure


def update_database_structure():
    pass


def migrate_datas():
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed

    conn = get_bind()

    ## TODO delete following in 2020
    ## Inserting default value for closure of 2019
    # If we are still in 2020
    if datetime.date.today() > datetime.date(2020, 12, 31):
        return

    # If 2019 closure doesn't exist
    query = session.query(AccountingClosure)
    query = query.filter(AccountingClosure.year == "2019")
    if query.all():
        return

    # We can insert the 2019 closure in order for the état de trésorerie
    # to be correct after the 31/12/2020
    op.execute("INSERT INTO accounting_closure (year, active) VALUE ('2019', '1');")
    mark_changed(session)


def upgrade():
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("accounting_closure")
    # ### end Alembic commands ###
